package com.jyu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyu.reggie.dto.DishDto;
import com.jyu.reggie.entity.Dish;
import com.jyu.reggie.entity.DishFlavor;
import com.jyu.reggie.mapper.DishMapper;
import com.jyu.reggie.mapper.EmployeeMapper;
import com.jyu.reggie.service.DishFlavorService;
import com.jyu.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * @description: 更新
     * @param dishDto
     * @return: void
     * @date: 2023/7/27 21:46
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());

        dishFlavorService.remove(queryWrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();

        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }

       /* flavors = flavors.stream().map( (item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());*/

        dishFlavorService.saveBatch(flavors);
    }

    /**
     * @description: 新增菜品，保存口味数据
     * @param dishDto
     * @return: void
     * @date: 2023/7/27 16:02
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);

        Long dishId = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map( (item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }

    /**
     * @description: 根据id 查询菜品信息和 对应口味信息
     * @param id
     * @return: com.jyu.reggie.dto.DishDto
     * @date: 2023/7/27 21:34
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish,dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(DishFlavor::getDishId, dish.getId());

        List<DishFlavor> list = dishFlavorService.list(queryWrapper);

        dishDto.setFlavors(list);

        return dishDto;
    }
}
